package codingforgreat.class13;

public class Class02_SuperWashingMachines {
    public static int findMinMoves(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        int N = arr.length;
        if(sum % N != 0){
            return  -1;
        }
        int ans = 0;
        int avg = sum / N;
        int leftSum = 0;
        for (int i = 0; i < N - 1; i++) {
          int leftRest = leftSum - i * avg;
          int rightRest = sum - leftSum - arr[i] - (N - 1 - i) * avg;
            if (leftRest < 0 && rightRest < 0) {
                ans = Math.max(ans, Math.abs(leftRest) + Math.abs(rightRest));
            } else {
                ans = Math.max(ans, Math.max(Math.abs(leftRest), Math.abs(rightRest)));
            }
            leftSum += arr[i];
        }
        return ans;
    }
}
